<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

// 响应式变量
const message = ref('')  // 输入框内容
const response = ref('')  // 响应内容
const logs = ref([])  // 日志数组
const loading = ref(false)  // 加载状态

// 添加日志
const addLog = (type, content) => {
  const log = {
    time: new Date().toLocaleTimeString(),
    type,
    content
  }
  logs.value.unshift(log)  // 新日志添加到顶部
}

// 清除响应和日志
const clear = () => {
  response.value = ''
  logs.value = []
  addLog('info', '已清除所有内容')
}

// 发送请求
const sendMessage = async () => {
  if (!message.value.trim()) {
    ElMessage.warning('请输入内容')
    return
  }

  response.value = ''
  loading.value = true
  addLog('info', `开始发送请求: ${message.value}`)

  try {
    const fetchResponse = await fetch('/api/memory_stream_build_product_title', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ message: message.value })
    })

    if (!fetchResponse.ok) {
      throw new Error(`HTTP error! status: ${fetchResponse.status}`)
    }

    if (!fetchResponse.body) {
      throw new Error('ReadableStream not supported')
    }

    const reader = fetchResponse.body.getReader()
    const decoder = new TextDecoder()
    let buffer = ''

    while (true) {
      const { value, done } = await reader.read()
      if (done) {
        loading.value = false
        addLog('info', '请求完成')
        break
      }

      const text = decoder.decode(value, { stream: true })
      console.log('收到原始数据:', text)  // 打印原始数据
      buffer += text

      // 处理缓冲区中的数据
      const lines = buffer.split('\n')  // 使用正确的换行符
      buffer = lines.pop() || '' // 保留最后一个不完整的行

      console.log('处理后的数据行:', lines)  // 打印分割后的数据行
      for (const line of lines) {
        const trimmedLine = line.trim()
        if (trimmedLine) {
          // 去掉 data: 前缀
          const cleanData = trimmedLine.replace(/^data:\s*/, '')
          console.log('处理后的数据:', cleanData)  // 打印处理后的数据
          
          // 如果不是结束标记
          if (cleanData !== 'done') {
            if (!response.value) {
              response.value = cleanData
            } else {
              response.value = response.value + cleanData
            }
            console.log('当前响应内容:', response.value)  // 打印当前响应内容
            addLog('success', `收到数据: ${cleanData}`)
          }
        }
      }
    }
  } catch (error) {
    loading.value = false
    const errorMessage = error.message || '未知错误'
    addLog('error', `请求失败: ${errorMessage}`)
    ElMessage.error(`请求失败: ${errorMessage}`)
    console.error('请求错误:', error)
  }
}
</script>

<template>
  <div class="stream-container">
    <div class="input-section">
      <el-input
        v-model="message"
        :disabled="loading"
        placeholder="请输入内容"
        @keyup.enter="sendMessage"
      >
        <template #append>
          <el-button 
            :loading="loading" 
            type="primary" 
            @click="sendMessage"
          >
            发送
          </el-button>
        </template>
      </el-input>
    </div>

    <div class="response-section">
      <div class="section-header">
        <h3>响应内容</h3>
        <el-button 
          type="primary" 
          link 
          @click="clear"
        >
          清除
        </el-button>
      </div>
      <div class="response-content" v-if="response">
        <span>{{ response }}</span>
      </div>
      <div class="response-content" v-else>
        <span class="placeholder">等待响应...</span>
      </div>
    </div>

    <div class="logs-section">
      <div class="section-header">
        <h3>日志记录</h3>
      </div>
      <div class="logs-content">
        <div 
          v-for="(log, index) in logs" 
          :key="index" 
          :class="['log-item', log.type]"
        >
          <span class="log-time">[{{ log.time }}]</span>
          <span class="log-content">{{ log.content }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.stream-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
}

.input-section {
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.response-section {
  margin-bottom: 20px;
}

.response-content {
  min-height: 100px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  white-space: pre-wrap;
  word-break: break-word;
}

.response-content .placeholder {
  color: #909399;
  font-style: italic;
}

.logs-content {
  max-height: 300px;
  overflow-y: auto;
  padding: 10px;
  background-color: #1e1e1e;
  border-radius: 4px;
  font-family: monospace;
}

.log-item {
  margin-bottom: 5px;
  color: #fff;
}

.log-time {
  color: #888;
  margin-right: 10px;
}

.log-item.error {
  color: #ff6b6b;
}

.log-item.success {
  color: #69db7c;
}

.log-item.info {
  color: #74c0fc;
}
</style>